<template>
  <div
    class="login page-register"
    :style="backgroundImage"
  >
    <div class="login-box">
      <div class="top">
        <div class="logo">
          <img
            :src="checkFileUrl(configuration.bsLoginLogoImg)"
            style="max-height: 45px;max-width: 174px;"
            alt
          >
          <span class="login-title">{{ configuration.bsTitleContent }}</span>
        </div>
      </div>
      <div class="mid">
        <el-form
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataRule"
          @submit.prevent
          @keyup.enter="onSubmit()"
        >
          <el-form-item prop="username">
            <el-input
              v-model="dataForm.username"
              v-input-rule
              class="info"
              maxlength="16"
              :placeholder="$t('sys.userName')"
            />
          </el-form-item>
          <el-form-item
            prop="password"
            class="password"
          >
            <el-input
              v-model="dataForm.password"
              v-input-rule
              class="info"
              type="password"
              maxlength="20"
              autocomplete="new-password"
              show-password
              :placeholder="$t('sys.password')"
            />
          </el-form-item>
          <el-form-item prop="mobile">
            <div class="mobile-box">
              <div class="mobile-int">
                <el-input
                  v-model="dataForm.mobile"
                  class="info"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  type="text"
                  maxlength="11"
                  :placeholder="$t('distribution.phoneNum')"
                >
                  <template #append>
                    <div
                      v-if="show"
                      class="get-code-btn"
                      @click="geCode()"
                    >
                      {{ $t('shop.getVerificationCode') }}
                    </div>
                    <div
                      v-else
                      class="get-code-btn"
                    >
                      {{ count }} s
                    </div>
                  </template>
                </el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="validCode">
            <el-input
              v-model="dataForm.validCode"
              class="info"
              maxlength="6"
              type="text"
              :placeholder="$t('home.verificationCode')"
            />
          </el-form-item>
          <el-form-item>
            <div class="btn-box">
              <div
                class="item-btn default-btn primary-btn"
                @click="onSubmit()"
              >
                {{ $t('homes.register') }}
              </div>
              <!-- <input type="button" :value="$t('homes.register')" @click="onSubmit()" /> -->
              <div class="bottom-row">
                <div
                  v-if="merchantRegisterProtocolSwitch === true"
                  class="protocol"
                >
                  <el-checkbox v-show="false" />
                  <el-checkbox
                    v-model="checked"
                    @change="changeCheckbox"
                  />
                  <div class="ag-txt">
                    {{ $t('homes.readConsent') }}<span
                      class="default-btn text-btn"
                      @click="queryRegisterProtocol"
                    >《{{ $t('homes.registerProtocol') }}》</span>
                  </div>
                </div>
                <div class="to-login">
                  {{ $t('homes.alreadyAccount') }}？<span
                    class="default-btn text-btn"
                    @click="toLogin"
                  >{{ $t('homes.goToLogin') }}</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="bottom">
        {{ configuration.bsCopyright }}
      </div>
    </div>

    <!-- 商家注册协议弹窗 -->
    <el-dialog
      v-model="protocolDialogVisible"
      :title="$t('homes.registerProtocol')"
      width="80%"
      top="6vh"
      :close-on-click-modal="false"
      :append-to-body="true"
      class="merchant-register-protocol"
    >
      <div class="registration-agreement">
        <div v-rich="registerProtocol" />
      </div>

      <template #footer>
        <div
          class="dialog-footer"
        >
          <!-- <el-button @click="protocolDialogVisible = false">关闭</el-button> -->
          <div
            class="default-btn primary-btn"
            @click="readAndAgree"
          >
            {{ $t('homes.readConsent') }}
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 注册成功提示弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="$t('text.tips')"
      width="350px"
      center
      class="success-dialog"
      :close-on-click-modal="false"
      :show-close="false"
      top="25vh"
    >
      <img
        src="@/assets/img/success.png"
        class="success-icon"
        alt
      >
      <div class="txt">
        {{ $t('homes.registerSuccess2') }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { isMobile, isUserName } from '@/utils/validate.js'
import { encrypt } from '@/utils/crypto.js'
import { formatConfigInfo } from '@/utils/website-config.js'
import { ElMessage } from 'element-plus'
import { validPassword } from '@/utils/validate'
import cookie from 'vue-cookies'

const webConfigStore = useWebConfigStore()
const router = useRouter()

const dataForm = reactive({
  username: '',
  password: '',
  mobile: '',
  validCode: ''
})

// 背景样式
const backgroundImage = reactive({
  width: '100%',
  height: '100%',
  backgroundSize: '100% 100%',
  position: 'fixed',
  top: 0
})

const configuration = ref({
  bsLoginLogoImg: null,
  bsLoginBgImg: null,
  bsCopyright: null,
  bsTitleContent: null,
  bsTitleImg: null,
  bsMenuTitleOpen: null,
  bsMenuTitleClose: null
})

const validateMobile = (rule, value, callback) => {
  if (!isMobile(value)) {
    callback(new Error($t('homes.InputCorrectPhone')))
  } else {
    callback()
  }
}
const validateUserName = (rule, value, callback) => {
  if (!isUserName(value.trim())) {
    callback(new Error($t('homes.InputCorrectUsername')))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (validPassword(value)) {
    callback()
  } else {
    callback(new Error($t('passwordVerification')))
  }
}
const dataRule = reactive({
  username: [
    { required: true, message: $t('home.userNameNoNull'), trigger: 'blur' },
    { validator: validateUserName, trigger: 'blur' }
  ],
  password: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  validCode: [
    { required: true, message: $t('home.capNoNull'), trigger: 'blur' }
  ]
})

onMounted(() => {
  getWebConfigData()
})

// 已阅读协议
const checked = ref(false)
// 多选框变化
const changeCheckbox = (val) => {
  checked.value = val
}

// 协议弹窗显隐
const protocolDialogVisible = ref(false)
// 注册协议
const registerProtocol = ref('')
/**
 * 商家注册协议
 */
const queryRegisterProtocol = () => {
  protocolDialogVisible.value = true
  http({
    url: http.adornUrl('/shop/shopUserRegister/getMerchantRegisterProtocol'),
    method: 'get'
  }).then(({ data }) => {
    registerProtocol.value = JSON.parse(data).content
  })
}

// 已阅读并同意注册协议
const readAndAgree = () => {
  protocolDialogVisible.value = false
  checked.value = true
}

const dataFormRef = ref(null)
let hadGotCode = false
let timer = null
const count = ref(null)
// 验证码相关
const show = ref(true)
/**
 * 获取验证码
 */
const geCode = () => {
  if (!dataForm.mobile || !isMobile(dataForm.mobile)) {
    dataFormRef.value?.validateField('mobile')
    return
  }
  if (hadGotCode) {
    return
  }
  // 判断值
  hadGotCode = true
  http({
    url: http.adornUrl('/shop/shopUserRegister/sendCode'),
    method: 'post',
    data: http.adornData({
      mobile: dataForm.mobile,
      shopAccount: 1 // 是否店铺账号： 1是
    })
  }).then(() => {
    const timeCount = 60
    if (!timer) {
      count.value = timeCount
      show.value = false
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          show.value = true
          clearInterval(timer)
          timer = null
          hadGotCode = false
        }
      }, 1000)
    }
  }).catch(() => {
    hadGotCode = false
  })
}

let isSubmit = false
// 注册成功弹窗显隐
const dialogVisible = ref(false)
const userStore = useUserStore()
const allinpayStore = useAllinpayStore()
// 提交表单
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (!checked.value) {
        ElMessage({
          message: $t('homes.readFirst') + '《' + $t('homes.registerProtocol') + '》',
          type: 'error',
          duration: 1500
        })
        return
      }
      if (isSubmit) {
        return
      }
      isSubmit = true
      http({
        url: http.adornUrl('/shop/shopUserRegister'),
        method: 'POST',
        data: http.adornData({
          username: dataForm.username.trim(),
          password: encrypt(dataForm.password),
          mobile: dataForm.mobile,
          validCode: dataForm.validCode
        })
      }).then(({ data }) => {
        dialogVisible.value = true
        cookie.set('bbcAuthorization_vs', data.accessToken)
        setTimeout(async () => {
          // toLogin()
          try {
            await userStore.login()
            // 重置菜单路由
            router.options.isAddDynamicMenuRoutes = false
          } catch (error) {
            dialogVisible.value = false
            return
          }
          if (userStore.shopStatus === 4 || userStore.shopStatus === 5 || userStore.isPassShop === 0) {
            // 未开店，跳转申请开店
            await router.push({
              path: '/shop-process'
            })
          } else {
            // 已开店，跳转首页
            await router.replace({
              name: 'home'
            })
          }
          // 获取并更新通联支付配置信息（平台开启通联支付会清除所有用户token，所以重新登录时更新通联支付配置信息）
          allinpayStore.getPaySettlementType().then((paySettlementType) => {
            if (paySettlementType === 1 && userStore.isPassShop) {
              // 通联支付开启后，登录时判断是否创建了通联会员，如果没有创建则创建通联会员
              http({
                url: http.adornUrl('/shop/shopDetail/info'),
                method: 'get',
                params: http.adornParams()
              }).then((res) => {
                if (res.isCreateMember !== 1) {
                  http({
                    url: http.adornUrl('/shop/shopDetail/createAllinpayMember'),
                    method: 'post'
                  })
                }
              })
            }
          })
          dialogVisible.value = false
        }, 1500)
        isSubmit = false
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

const merchantRegisterProtocolSwitch = ref(true)
// 获取网站配置信息
const getWebConfigData = () => {
  http({
    url: http.adornUrl('/sys/webConfig/getActivity'),
    method: 'get'
  }).then(({ data }) => {
    data = formatConfigInfo(data)
    webConfigStore.addData(data)
    configuration.value = data
    backgroundImage.backgroundImage = `url(${checkFileUrl(data.bsLoginBgImg)})`
    merchantRegisterProtocolSwitch.value = data.merchantRegisterProtocolSwitch
    if (merchantRegisterProtocolSwitch.value === false) {
      readAndAgree()
    }
  })
}

// 去注册
const toLogin = () => {
  router.push({ path: '/login' })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
